package com.xiaoxu.springboot.modules.test.service.impl;

import com.xiaoxu.springboot.modules.common.vo.Result;
import com.xiaoxu.springboot.modules.common.vo.Search;
import com.xiaoxu.springboot.modules.test.dao.StudentDao;
import com.xiaoxu.springboot.modules.test.entity.Student;
import com.xiaoxu.springboot.modules.test.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.Collections;
import java.util.List;
import java.util.Optional;

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentDao studentDao;
    @Override
    @Transactional
    public Result<Student> insertStudent(Student student) {
        studentDao.saveAndFlush(student);

        return new Result<>(Result.ResultStatus.SUCCESS.code,"success");
    }

    @Override
    @Transactional
    public Result<Student> updateStudent(Student student) {
        studentDao.saveAndFlush(student);
        return new Result<>(Result.ResultStatus.SUCCESS.code,"success");
    }

    @Override
    @Transactional
    public Result<Object> deleteStudentById(Integer id) {
        studentDao.deleteById(id);
        return new Result<>(Result.ResultStatus.SUCCESS.code,"sucess");
    }

    @Override
    @Transactional
    public Student getStudentById(Integer id) {

        return studentDao.getById(id);
    }

    @Override
    @Transactional
    public Page selectByseach(Search search) {
        search.init();
        //分页和排序功能
        Sort sort=Sort.by(
                search.getDirection().toLowerCase().equals("asc")?
                Sort.Direction.ASC:Sort.Direction.DESC,
                search.getSort()
        );
        PageRequest pageRequest=PageRequest.of(
                search.getCurrentPage()-1,
                search.getPageSize(),
                sort
        );
        //查询模板
        Student student=new Student();
        student.setStudentName(search.getKeyword());
        ExampleMatcher macher=ExampleMatcher
                .matchingAny()
                .withMatcher("studentName",matcher -> matcher.contains())
                .withIgnorePaths("id");
        //根据实体 bean 属性以及设定的模板匹配器规则，到数据库查询
        //设置查询条件
        Example<Student> example=Example.of(student,macher);
        return studentDao.findAll(example,pageRequest);
    }

    @Override
    @Transactional
    public List<Student> getStudentsByStudentName(String studentName) {
        return Optional.ofNullable(studentDao.findByStudentName(studentName)).orElse(Collections.emptyList());
    }
}
